package com.zqxq.lottery.cms.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.zqxq.auth.cache.UserFuncCache;
import com.zqxq.auth.entity.po.UserAdmin;
import com.zqxq.common.constant.Result;
import com.zqxq.lottery.cms.feign.LotteryServerFeignClient;
import com.zqxq.lottery.entity.bo.user.UserCashBO;
import com.zqxq.lottery.entity.bo.user.UserCashSearchBO;
import com.zqxq.lottery.entity.bo.user.UserInfoCMSBO;
import com.zqxq.lottery.entity.bo.user.UserPrizeBO;
import com.zqxq.lottery.entity.vo.user.UserCashVO;
import com.zqxq.lottery.entity.vo.user.UserInfoCMSVO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Api(value = "用户管理",tags = "用户管理")
@RestController
@Slf4j
@RequestMapping(value = "/user", produces = "application/json")
public class UserController {

    @Autowired
    private LotteryServerFeignClient lotteryServerFeignClient;
    @Autowired
    private UserFuncCache userFuncCache;

    @ApiOperation(value = "中奖管理-分页查询", notes="中奖管理-分页查询")
    @PostMapping(value="/userprize/page")
    public Result queryUserPrizePage(UserPrizeBO search){
        return lotteryServerFeignClient.queryUserPrizePage(search);
    }

    @ApiOperation(value = "用户资金-分页查询", notes="用户资金-分页查询")
    @PostMapping(value="/usercash/page")
    public Result queryUserCashPage(UserCashBO search){
        return lotteryServerFeignClient.queryUserCashPage(search);
    }

    @ApiOperation(value = "用户资金-导出", notes="用户资金-导出")
    @PostMapping(value="/usercash/export")
    public void exportUserCash(UserCashSearchBO search, HttpServletResponse response){
        Result<List<UserCashVO>> result = lotteryServerFeignClient.queryUserCash(search);
        List<UserCashVO> list = result.getData();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("交易明细表");
        String fileName = "userCashInfo"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        String[] headers = {"交易时间", "手机号", "交易额（趣豆）", "余额（趣豆）", "交易类型", "状态", "充值方式"};
        //headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        //在表中存放查询到的数据放入对应的列
        for (UserCashVO userCashVO : list) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(userCashVO.getCreateTime());
            String type = "";
            String status = "";
            String payWay = "";
            row1.createCell(1).setCellValue(userCashVO.getMobile());
            row1.createCell(2).setCellValue(userCashVO.getPayAmount());
            row1.createCell(3).setCellValue(userCashVO.getRemainder());
            switch (userCashVO.getType()){
                case "1":
                    type = "充值";
                    break;
                case "2":
                    type = "提现";
                    break;
                case "3":
                    type = "奖金";
                    break;
                case "4":
                    type = "竞猜";
                    break;
                case "5":
                    type = "退款";
                    break;
                case "6":
                    type = "佣金";
                    break;
                case "7":
                    type = "赠送";
                    break;
                case "8":
                    type = "换钻";
                    break;
                case "9":
                    type = "换物";
                    break;
                case "10":
                    type = "抽奖";
                    break;
                case "11":
                    type = "兑换";
                    break;
            }
            switch (userCashVO.getStatus()){
                case "1":
                    status = "待审核";
                    break;
                case "2":
                    status = "处理中";
                    break;
                case "3":
                    status = "失败";
                    break;
                case "4":
                    status = "成功";
                    break;
            }
            switch (userCashVO.getPayWay()){
                case "0":
                    payWay = "系统";
                    break;
                case "1":
                    payWay = "支付宝";
                    break;
                case "2":
                    payWay = "银行卡";
                    break;
                case "3":
                    payWay = "奖金";
                    break;
                case "4":
                    payWay = "中奖资金";
                    break;
                case "5":
                    payWay = "充值资金";
                    break;
                case "6":
                    payWay = "微信";
                    break;
                case "7":
                    payWay = "平台赠送资金";
                    break;
                case "8":
                    payWay = "钻石";
                    break;
                case "99":
                    payWay = "其它";
                    break;
            }
            row1.createCell(4).setCellValue(type);
            row1.createCell(5).setCellValue(status);
            row1.createCell(6).setCellValue(payWay);
            rowNum++;
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        try {
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "用户充值-分页查询", notes="用户充值-分页查询")
    @PostMapping(value="/usercash/pageCZ")
    public Result queryUserCashPageCZ(UserCashBO search){
        return lotteryServerFeignClient.queryUserCashPageCZ(search);
    }

    @ApiOperation(value = "用户提现-分页查询", notes="用户提现-分页查询")
    @PostMapping(value="/usercash/pageTX")
    public Result queryUserCashPageTX(UserCashBO search){
        return lotteryServerFeignClient.queryUserCashPageTX(search);
    }

    @ApiOperation(value = "用户提现-获取详情", notes="用户提现-获取详情")
    @PostMapping(value="/usercash/getTX")
    public Result<UserCashVO> getUserCashTX(Long id){
        return lotteryServerFeignClient.getUserCashTX(id);
    }

    @ApiOperation(value = "用户提现-处理提现", notes="用户提现-处理提现")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID", required = true, paramType = "query", dataType = "Long")
            ,@ApiImplicitParam(name = "status", value = "状态：0 拒绝，1同意", required = true, paramType = "query", dataType = "Integer")
            ,@ApiImplicitParam(name = "token_id", value = "授权token", required = true, paramType = "query", dataType = "String")
    })
    @PostMapping(value="/usercash/auditDrawCash")
    public Result auditDrawCash(Long orderId, Integer status, String token_id){
        UserAdmin userAdmin = userFuncCache.getUserAdmin(token_id);
        String auditUser = null;
        if(userAdmin != null){
            auditUser = userAdmin.getUser_name();
        }
        return lotteryServerFeignClient.auditDrawCash(orderId, status, auditUser);
    }

    /***********************************************用户*******************************************************/
    @ApiOperation("获取用户分页信息")
    @PostMapping("/queryUserPageList")
    public Result<Page<UserInfoCMSVO>> queryUserPageList(UserInfoCMSBO bo){
        return lotteryServerFeignClient.queryUserPageList(bo);
    }
    @ApiOperation("获取用户详情")
    @PostMapping("/getUserCMSVO")
    public Result<UserInfoCMSVO> getUserCMSVO(Long userId, @RequestParam(defaultValue = "1") Integer pageNo,@RequestParam(defaultValue = "10") Integer pageSize){
        return lotteryServerFeignClient.getUserCMSVO(userId,pageNo,pageSize);
    }
    @ApiOperation("获取代理数据统计")
    @PostMapping("/getAgentDataStatistics")
    public Result getAgentDataStatistics(@ApiParam(value = "用户id",required = true) Long userId,
                                         @ApiParam(value = "开始时间",required = false) String startTime,
                                         @ApiParam(value = "结束时间",required = false) String endTime,
                                         @ApiParam(value = "pageNo",required = true) @RequestParam(defaultValue = "1") Integer pageNo,
                                         @ApiParam(value = "pageSize",required = true) @RequestParam(defaultValue = "10") Integer pageSize){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("pageNo",pageNo);
        paramMap.put("pageSize",pageSize);
        paramMap.put("startTime",startTime);
        paramMap.put("endTime",endTime);
        paramMap.put("userId",userId);
        return lotteryServerFeignClient.getAgentDataStatistics(paramMap);
    }

    @ApiOperation(value = "发放用户优惠券", notes="发放用户优惠券")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "couponId", value = "优惠券ID", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "mobiles", value = "电话号码", required = true, paramType = "query", dataType = "String")
    })
    @PostMapping(value="/usercoupon/send")
    public Result sendCoupons(String mobiles,Long couponId){
        return lotteryServerFeignClient.sendCoupons(mobiles,couponId);
    }
    @ApiOperation(value = "账号封禁/解禁", notes="账号封禁/解禁")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "enabled", value = "是否禁用", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping(value="/closureOrRelease")
    public Result closureOrRelease(Long userId,Integer enabled){
        return lotteryServerFeignClient.closureOrRelease(userId,enabled);
    }

    @ApiOperation(value = "用户-excel导出", notes="用户-excel导出")
    @PostMapping("/excelBatchExport")
    public void excelBatchExportUser(UserInfoCMSBO bo, HttpServletResponse response){
        Result<List<UserInfoCMSVO>> result = lotteryServerFeignClient.excelBatchExportUser(bo);
        List<UserInfoCMSVO> list = result.getData();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("用户信息表");
        String fileName = "productInfo"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        String[] headers = {"ID", "手机号", "姓名", "性别", "年龄", "所在城市", "来源","渠道","appKey","身份证编号", "支付宝账号", "邀请人", "可用余额（趣豆）","累计充值（元）","注册时间"};
        //headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        //在表中存放查询到的数据放入对应的列
        for (UserInfoCMSVO userInfo : list) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(userInfo.getUserId());
            row1.createCell(1).setCellValue(userInfo.getMobile());
            row1.createCell(2).setCellValue(userInfo.getRealName());
            String sex = "未知";
            String source = "";
            if("1".equals(userInfo.getSex())){
                sex = "女";
            }else if("2".equals(userInfo.getSex())){
                sex = "男";
            }
            if("1".equals(userInfo.getSource())){
                source = "Android";
            }else if("2".equals(userInfo.getSource())){
                source = "IOS";
            }else if("3".equals(userInfo.getSource())){
                source = "H5";
            }
            row1.createCell(3).setCellValue(sex);
            row1.createCell(4).setCellValue(userInfo.getAge());
            row1.createCell(5).setCellValue(userInfo.getCity());
            row1.createCell(6).setCellValue(source);
            row1.createCell(7).setCellValue(userInfo.getChannel());
            row1.createCell(8).setCellValue(userInfo.getAppKey());
            row1.createCell(9).setCellValue(userInfo.getIdCard());
            row1.createCell(10).setCellValue(userInfo.getAlipayAccount());
            row1.createCell(11).setCellValue(userInfo.getInviterPhone());
            row1.createCell(12).setCellValue(userInfo.getBalance());
            row1.createCell(13).setCellValue(userInfo.getRechargeSum());
            row1.createCell(14).setCellValue(userInfo.getCreateTime());
            rowNum++;
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        try {
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
